<template>
  <nav class="navbar navbar-default">
    <div class="container">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <router-link class="navbar-brand" to="/">TaskSaas</router-link>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <!--              <li><a href="#">产品功能</a></li>-->
          <!--                    <li><a href="#">企业方案</a></li>-->
          <li><a href="#">帮助文档</a></li>
          <!--                     <li><a href="#">价格</a></li>-->
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <!--          {% if request.web.user %}-->
          <li v-show="this.token" class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
               aria-expanded="false">{{ this.username }}<span class="caret"></span></a>
            <ul class="dropdown-menu">
              <li><a href="profile">用户设置</a></li>
              <li role="separator" class="divider"></li>
              <li><a href="sys_setting">系统设置</a></li>
              <li role="separator" class="divider"></li>
              <li><a href="#" @click="this.doLogout">用户注销</a></li>
            </ul>
          </li>
          <!--          {% else %}-->
          <li v-show="!this.token">
            <a href="#" lay-on="login-window">登 陆</a>
          </li>
          <li v-show="!this.token">
            <!--            <a href="/register">注 册</a>-->
            <a href="#" lay-on="register-window" @click="this.login_count">注 册 (注册次数:{{ pv }})</a>
          </li>
          <li>
            <!--            <a href="#" @click="$store.commit('increment')"> 版本赞赞赞++ </a>-->
            <!--            <a  href="#" @click="$store.dispatch('increment')"> 点赞点赞++ </a>-->
          </li>
          <li>
            <!--            <a href="#">{{ count }}</a>-->
          </li>

          <!--          {% endif %}-->
        </ul>

      </div>
    </div>
  </nav>


<!--  <router-view></router-view>-->

</template>

<script>

import {loginPass} from '@/api/auth.js'
import {mapActions, mapGetters} from "vuex";
import {setTokenExpired, setUserName} from "@/utils/auth.js";
import {createRouter as $router} from "vue-router";

export default {
  name: "Navbar",
  data() {
    return {}
  },
  computed: {
    count() {
      return this.$store.state.count
    },
    pv() {
      return this.$store.state.pv
    },
    store() {
      return this.$store
    },

    ...mapGetters([
      'token',
      'username',
    ])
  },
  methods: {
    goLogin() {
      $router.push('/login')
    },
    goRegister() {
    },
    goIndex() {
      $router.push('/')
    },
    doLogout() {
      this.Logout()
    },
    ...mapActions([
      'asyncLogin',
      'Register',
      'increment',
      'login_count',
      'Logout'
    ])
  },
  mounted() {
    var mstore = this.store
    var asyncLogin = this.asyncLogin
    var register = this.Register
    layui.use(function () {
      var $ = layui.$;
      var layer = layui.layer;
      var util = layui.util;
      var form = layui.form;
      var loginWindow;
      var registerWindow;
      // 事件
      util.on('lay-on', {
        'login-window': function () {
          loginWindow = layer.open({
            type: 1,
            area: '350px',
            resize: false,
            shadeClose: true,
            title: '欢迎登陆使用TaskSaas',
            content: `
          <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
            <div class="demo-login-container">
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                  </div>
                  <input type="text" name="username" value="" lay-verify="required" placeholder="用户名" lay-reqtext="请填写用户名" autocomplete="off" class="layui-input" lay-affix="clear">
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                  </div>
                  <input type="password" name="password" value="" lay-verify="required" placeholder="密   码" lay-reqtext="请填写密码" autocomplete="off" class="layui-input" lay-affix="eye">
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-row">
                  <div class="layui-col-xs7">
                    <div class="layui-input-wrap">
                      <div class="layui-input-prefix">
<!--                        <i class="layui-icon layui-icon-vercode"></i>-->
                      </div>
<!--                      <input type="text" name="captcha" value="" lay-verify="required" placeholder="验证码" lay-reqtext="请填写验证码" autocomplete="off" class="layui-input" lay-affix="clear">-->
                    </div>
                  </div>
<!--                  <div class="layui-col-xs5">-->
<!--                    <div style="margin-left: 10px;">-->
<!--                      <img src="https://www.oschina.net/action/user/captcha" onclick="this.src='https://www.oschina.net/action/user/captcha?t='+ new Date().getTime();">-->
<!--                    </div>-->
<!--                  </div>-->
                </div>
              </div>
              <div class="layui-form-item">
                <input type="checkbox" name="remember" lay-skin="primary" title="记住密码">
                <a href="#forget" style="float: right; margin-top: 7px;">忘记密码？</a>
              </div>
              <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="demo-login">登录</button>
              </div>
              <div class="layui-form-item demo-login-other">
                <label>社交账号登录</label>
                <span style="padding: 0 21px 0 6px;">
<!--                  <a href="javascript:;"><i class="layui-icon layui-icon-login-qq" style="color: #3492ed;"></i></a>-->
                  <a href="javascript:;"><i class="layui-icon layui-icon-login-wechat" style="color: #4daf29;"></i></a>
<!--                  <a href="javascript:;"><i class="layui-icon layui-icon-login-weibo" style="color: #cf1900;"></i></a>-->
                </span>
                或
                <a href="#" lay-on="register-window">注册账号</a>
                </span>

              </div>
            </div>
          </div>
        `,
            success: function () {
              // 对弹层中的表单进行初始化渲染
              form.render();
              // 表单提交事件
              form.on('submit(demo-login)', async function (data) {
                var field = data.field; // 获取表单字段值
                // 显示填写结果，仅作演示用
                // layer.alert(JSON.stringify(field), {
                //   title: '当前填写的字段值'
                // });
                let formJson = JSON.parse(JSON.stringify(field))
                console.log('login form :', formJson)
                let loginRes = await asyncLogin(formJson)
                console.log('loginRes', loginRes)
                // console.log('loginRes.data', loginRes.data)
                if (loginRes.data.code === 200 && loginRes.data.data.tokenHeader === 'Ukyo') {
                  console.log('login ok')
                  layer.msg('login ok')
                  mstore.commit('SET_TOKEN', loginRes.data.data.token)
                  mstore.commit('userinfo', {'username': loginRes.data.data.token})
                  setTokenExpired(loginRes.data.data.token, loginRes.data.data.expiresIn)
                  setUserName(formJson.username)
                  layer.close(loginWindow);
                  mstore.commit('userinfo', {'username': formJson.username})
                } else {
                  layer.msg(loginRes.data.data)
                }
                // 此处可执行 Ajax 等操作
                // …
                return false; // 阻止默认 form 跳转
              });
            }
          });

          layer.close(registerWindow);

          //when press esc (event27) then close prompt of editor
          // $(document).keyup(function (event) {
          //   if (event.which === 27) {
          //     //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算
          //     layer.close(loginWindow);
          //   }
          // })
        },
        'register-window': function () {
          registerWindow = layer.open({
            type: 1,
            area: '350px',
            resize: false,
            shadeClose: true,
            title: '欢迎注册使用TaskSaas',
            content: `
          <div class="layui-form" lay-filter="filter-test-layer" style="margin: 16px;">
            <div class="demo-login-container">
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-username"></i>
                  </div>
                  <input type="text" id="usernameIptRegi" name="username" value="" lay-verify="required" placeholder="用户名" lay-reqtext="请填写用户名" autocomplete="off" class="layui-input" lay-affix="clear">
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                  </div>
                  <input type="password" id="passwdIptRegi" name="password" value="" lay-verify="required" placeholder="密   码" lay-reqtext="请填写密码" autocomplete="off" class="layui-input" lay-affix="eye">
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-input-wrap">
                  <div class="layui-input-prefix">
                    <i class="layui-icon layui-icon-password"></i>
                  </div>
                  <input type="password" id="passwdIpt2Regi" name="passwordRepeat" value="" lay-verify="required" placeholder="重 复 密 码" lay-reqtext="请重复填写密码" autocomplete="off" class="layui-input" lay-affix="eye">
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-row">
                  <div class="layui-col-xs7">
                    <div class="layui-input-wrap">
                      <div class="layui-input-prefix">
<!--                        <i class="layui-icon layui-icon-vercode"></i>-->
                      </div>
<!--                      <input type="text" name="captcha" value="" lay-verify="required" placeholder="验证码" lay-reqtext="请填写验证码" autocomplete="off" class="layui-input" lay-affix="clear">-->
                    </div>
                  </div>
<!--                  <div class="layui-col-xs5">-->
<!--                    <div style="margin-left: 10px;">-->
<!--                      <img src="https://www.oschina.net/action/user/captcha" onclick="this.src='https://www.oschina.net/action/user/captcha?t='+ new Date().getTime();">-->
<!--                    </div>-->
<!--                  </div>-->
                </div>
              </div>
              <div class="layui-form-item">
                <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="page-register">注册</button>
              </div>
              <div class="layui-form-item demo-login-other">
                         <a href="#" lay-on="login-window">去登陆</a>
                        </span>
              </div>
            </div>
          </div>
        `,
            success: function () {
              // 对弹层中的表单进行初始化渲染
              form.render();
              // 表单提交事件
              form.on('submit(page-register)', async function (data) {
                var field = data.field; // 获取表单字段值
                // 显示填写结果，仅作演示用
                // layer.alert(JSON.stringify(field), {
                //   title: '当前填写的字段值'
                // });
                let formJson = JSON.parse(JSON.stringify(field))
                if (formJson.password !== formJson.passwordRepeat) {
                  layer.msg('两次密码输入不匹配')
                  return false
                }
                let regRes = await register(formJson)
                // console.log('regRes', regRes)
                // if (regRes.code === 200) {
                //   console.log('reg ok')
                //   layer.msg('reg ok')
                layer.close(registerWindow);
                // mstore.commit('userinfo', {'username': formJson.username})
                // }else{
                //   layer.msg()
                // }
                // 此处可执行 Ajax 等操作
                // …
                return false; // 阻止默认 form 跳转
              });
            }
          });
          layer.close(loginWindow);
        },
      })
    })
  },

}

async function doLogin(data) {
  console.log('doLogin……')
  return loginPass(data);
}


</script>

<style scoped>

/*.navbar-default {*/
/*  border-radius: 4px;*/
/*}*/
</style>
